#include <QFileDialog>
#include <QMessageBox>
#include "DialogImport.hpp"
#include "ui_DialogImport.h"
#include "Is.hpp"

DialogImport::DialogImport(std::list<SpriteSheet*>& imageList, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogImport),
    _imageList(imageList),
    _spritesLoaded(false)
{
    ui->setupUi(this);
    initWidgets();
}

DialogImport::~DialogImport()
{
    delete ui;
}

void    DialogImport::initWidgets()
{
    QObject::connect(ui->pushButtonBrowse, SIGNAL(clicked()), this, SLOT(buttonActionBrowse()));
    QObject::connect(ui->pushButtonImport, SIGNAL(clicked()), this, SLOT(buttonActionImport()));
    QObject::connect(ui->pushButtonCancel, SIGNAL(clicked()), this, SLOT(close()));
}

void    DialogImport::buttonActionBrowse()
{
    QString	result = QFileDialog::getOpenFileName(this, QString("Load tiles..."), QString("."), QString("Image (*.png *.jpg *.bmp)"));

    if (result != "")
    {
        ui->lineEditFilePath->setText(result);
    }
}

void    DialogImport::buttonActionImport()
{
    QString     filePath = ui->lineEditFilePath->text();

    if (filePath != "")
    {
        QString     tileSheetName = ui->lineEditTileSheetName->text();

        if (tileSheetName != "")
        {
            if (SpriteSheet::alreadyLoaded(_imageList, tileSheetName) == false)
            {
                QString     tileWidth = ui->lineEditTileWidth->text();
                QString     tileHeight = ui->lineEditTileHeight->text();

                if (tileWidth != "" && tileHeight != "" && Is::isNum(tileWidth) && Is::isNum(tileHeight))
                {
                    TileCutter  cutter(_imageList);

                    cutter.cutSprite(tileSheetName, filePath, tileWidth.toInt(), tileHeight.toInt());
                    _spritesLoaded = true;
                    this->close();
                }
                else
                    QMessageBox::critical(this, "Error", "Please fill the fields tile width and tile height with integer values.");
            }
            else
                QMessageBox::critical(this, "Error", "A sprite sheet already has this name. Please choose another one.");
        }
        else
            QMessageBox::critical(this, "Error", "Please enter a tile sheet name.");
    }
    else
        QMessageBox::critical(this, "Error", "Please choose a file to import.");
}

bool    DialogImport::spritesLoaded() const
{
    return _spritesLoaded;
}
